package net.lsr.demo.server;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.lsr.demo.helper.Constant;
import net.lsr.demo.helper.IPHelper;
import net.lsr.demo.helper.ResultGenerator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * desc: IP接收器
 * @author lsr
 * @version 2014年6月5日
 */
@Controller
@RequestMapping("/ip")
public class IPReceiver {
	private static final Logger logger = LoggerFactory.getLogger(IPReceiver.class);
	@Autowired
	private ResultGenerator resultGenerator;
	@Autowired
	private IPHelper ipHelper;
	
	/**
	 * 接收上报IP
	 * @return
	 */
	@RequestMapping(value="/report", method = {RequestMethod.POST, RequestMethod.GET})
	@ResponseBody
	public Map<String, Object> receive(HttpServletRequest request, HttpServletResponse response){
	    String remoteIP = ipHelper.getIP(request);
		String branch = request.getParameter("location");
		logger.info("receive [ip:{},branch:{}]", new Object[]{remoteIP, branch});
		if(StringUtils.isEmpty(remoteIP))
			resultGenerator.generateResult(Constant.IP_CODE_EMPTY_IP, "IP为空");
		if(!ipHelper.isValidIPV4(remoteIP))
			resultGenerator.generateResult(Constant.IP_CODE_INVALID_IP, "IP无效");
		if(StringUtils.isEmpty(branch))
			resultGenerator.generateResult(Constant.IP_CODE_EMPTY_LOCATION, "地点为空");
		
		return resultGenerator.generateResult(Constant.OK, "");
	}
}
